<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>钉钉推送配置</title>
</head>
<body>
  <h2>钉钉推送配置</h2>
  <a href="{{ url_for('index') }}">← 返回主配置</a>
  <form method="post" action="{{ url_for('save_dingtalk') }}">
    <div id="dingtalk-container">
      {% for group in dingtalk_config %}
      <div class="dingtalk-row">
        群名称: <input type="text" name="group_name" value="{{ group.group_name }}">
        Webhook: <input type="text" name="webhook" value="{{ group.webhook }}">
        签名: <input type="text" name="secret" value="{{ group.secret }}">
        @手机号: <input type="text" name="at_mobiles" value="{{ group.at_mobiles | join(',') }}">
        <button type="button" onclick="testDingTalk(this)">调试</button>
      </div>
      {% endfor %}
    </div>
    <button type="button" onclick="addRow()">新增</button>
    <button type="submit">保存</button>
  </form>

  <script>
    function addRow() {
      const container = document.getElementById('dingtalk-container');
      const div = document.createElement('div');
      div.className = "dingtalk-row";
      div.innerHTML = `
        群名称: <input type="text" name="group_name">
        Webhook: <input type="text" name="webhook">
        签名: <input type="text" name="secret">
        @手机号: <input type="text" name="at_mobiles" placeholder="多个手机号用英文逗号分隔">
        <button type="button" onclick="testDingTalk(this)">调试</button>
      `;
      container.appendChild(div);
    }

    function testDingTalk(button) {
      const row = button.parentElement;
      const webhook = row.querySelector("input[name='webhook']").value.trim();
      const secret = row.querySelector("input[name='secret']").value.trim();
      const atMobiles = row.querySelector("input[name='at_mobiles']").value
        .split(',')
        .map(m => m.trim())
        .filter(m => m.length > 0);
      const groupName = row.querySelector("input[name='group_name']").value.trim();

      if (!webhook) {
        alert("⚠️ Webhook 地址不能为空");
        return;
      }

      // 构造发送数据
      const payload = {
        webhook: webhook,
        secret: secret,
        at_mobiles: atMobiles,
        group_name: groupName || "测试群"
      };

      // 发送请求到后端
      fetch("/send-test-dingtalk", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          alert("✅ 测试消息发送成功！");
        } else {
          alert("❌ 发送失败: " + (data.message || "未知错误"));
        }
      })
      .catch(err => {
        console.error(err);
        alert("❌ 网络错误，请查看控制台");
      });
    }
  </script>
</body>
</html>